import json

from django.shortcuts import render,HttpResponse
from .models import EsTools

# Create your views here.

es = EsTools()

def index(request):

    #接收用户的搜索参数
    args = request.GET.get('args',None)
    #获取用户的页码
    page = request.GET.get('page',0)

    if args:
        body = {
            "query":{
                "multi_match":{
                    "fields":["fang_address","fang_title"],
                    "query":args
                }
            },
            "from":int(page) * 10,
            "size":10
        }

        data = es.query_data(body)
        #print(type(data))   #<class 'elastic_transport.ObjectApiResponse'>
        #对数据格式做处理
        #拿到耗费时间
        took = dict(data)['took']
        #拿到查询的数据条数
        value = dict(data)['hits']['total']['value']
        #拿到房屋的元数据
        metadata = dict(data)['hits']['hits']
        metadata = json.dumps(metadata).replace("_","")
        #将数据整合返回到list页面
        contents = {}
        #将数据填充进字典
        contents['took'] = took
        contents['value'] = value
        contents['metadata'] = json.loads(metadata)
        #用户查询的参数传过去
        contents['args'] = args
        #页码传过去
        contents['pre_page'] = int(page) - 1 if int(page) > 0 else 0
        contents['next_page'] = int(page) + 1

        return render(request,'list.html',contents)
    return render(request,"index.html")